package com.zhang.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.model.user.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.zhang.yygh.common.exception.YYGHException;
import com.zhang.yygh.common.result.R;
import com.zhang.yygh.common.utils.JwtHelper;
import com.zhang.yygh.user.service.UserInfoService;
import com.zhang.yygh.user.util.ConstantPropertiesUtil;
import com.zhang.yygh.user.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/userinfo/wx")
public class WeixinController {

    @Autowired
    private ConstantPropertiesUtil constantPropertiesUtil;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取微信登录参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getWeixinData() throws UnsupportedEncodingException {
        String redirectUri = URLEncoder.encode(constantPropertiesUtil.getRedirectUrl(), "UTF-8");
        Map<String, Object> map = new HashMap<>();
        map.put("appid", constantPropertiesUtil.getAppId());
        map.put("redirect_uri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
        return R.ok().data(map);
    }

    @GetMapping("/callback")
    public String callback(String code,String state) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer append = stringBuffer.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=%s");
        String url = String.format(append.toString(), constantPropertiesUtil.getAppId(), constantPropertiesUtil.getAppSecret(), code, "authorization_code");
        String result = HttpClientUtils.get(url);
        System.out.println("返回结果为："+result);
        /*Gson gson = new Gson();
        Map map = gson.fromJson(result, Map.class);
        map.get();*/
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if (userInfo==null){ //添加数据
            String url2="https://api.weixin.qq.com/sns/userinfo?access_token="+jsonObject.getString("access_token")+"&openid="+openid;
            JSONObject jsonObject1 = JSONObject.parseObject(HttpClientUtils.get(url2));
            String nickname = jsonObject1.getString("nickname");
            //String headimgurl = jsonObject1.getString("headimgurl");

            System.out.println(nickname);
            userInfo = new UserInfo();
            userInfo.setOpenid(openid);
            //微信昵称
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
        }
        Integer status = userInfo.getStatus();
        if (status==0){
            throw new YYGHException(20001,"该用户已被锁定");
        }

        //返回name和token字符串
        Map<String,String> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);

        //1.如果没有绑定过手机号：往前端页面携带一个openid
        //2.如果已经绑定过手机号：往前端页面不用携带一个openid
        if (StringUtils.isEmpty(userInfo.getPhone())){
            map.put("openid",openid);
        }else {
            map.put("openid","");
        }

        //跳转到前端页面
        return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");

    }
}
